import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes, allAsyncRoutes, anyRoutes } from "@/router/routes";
import { loginApi, getUserInfoApi, loguotApi } from "@/api/acl/login";
import type { RouteRecordRaw } from "vue-router";
import cloneDeep from "lodash/cloneDeep";
import router from "@/router";
const filterAsyncRoutes = (
  allAsyncRoutes: Array<RouteRecordRaw>,
  routes: string[]
) => {
  return allAsyncRoutes.filter((route) => {
    if (routes.includes(route.name as string)) {
      if (route.children && route.children.length) {
        const childrenRoutes = filterAsyncRoutes(route.children, routes);
        route.children = childrenRoutes;
      }
      return true;
    }
    return false;
  });
};

// 将过滤后的路由添加到路由对象中
function addRoutes(routes: Array<RouteRecordRaw>) {
  routes.forEach((route) => {
    router.addRoute(route);
  });
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    buttons: [],
    routes: [],
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     if (username === "admin" && password === "111111") {
      //       const token = "token-atguigu";
      //       setToken(token);
      //       this.token = token;
      //       resolve(token);
      //     } else {
      //       reject(new Error("用户名或密码错误!"));
      //       ElMessage.error("用户名或密码错误!");
      //     }
      //   }, 1000);
      // });
      const { token } = await loginApi(username, password);
      setToken(token); //将数据存储到localStroage中(存在硬盘中读取更慢)
      this.token = token;
      // 真实需求：除了登录接口  其他请求都需要token参数
    },

    async getInfo() {
      // return new Promise((resolve, reject) => {

      //   setTimeout(() => {
      //     this.name = "admin";
      //     this.avatar =
      //       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
      //     this.menuRoutes = staticRoutes;
      //     resolve({ name: this.name, avatar: this.avatar, token: this.token });
      //   }, 1000);
      // });
      const res = await getUserInfoApi();

      // 动态路由表，通过用户路由权限值进行遍历过滤，保留用户拥有访问权限的路由表
      const filterRoutes = filterAsyncRoutes(
        cloneDeep(allAsyncRoutes),
        res.routes
      );

      addRoutes([...filterRoutes, ...anyRoutes]);

      // 将用户数据存储起来
      this.name = res.name;
      this.avatar = res.avatar;
      this.routes = res.routes;
      this.buttons = res.buttons;
      // 左侧菜单读取数据进行遍历生成菜单
      this.menuRoutes = [...staticRoutes, ...filterRoutes];
    },

    async logout() {
      await loguotApi();
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
      this.buttons = [];
      this.routes = [];
    },
  },
});
